package models

import (
	"github.com/beego/beego/v2/client/orm"
)

// Permission 权限模型
type Permission struct {
	BaseModel
	Name        string `orm:"size(64);" json:"name"`
	Description string `orm:"size(255)" json:"description"`
	Module      string `orm:"size(64)" json:"module"`      // 所属模块
	Type        string `orm:"size(20)" json:"type"`        // 权限类型：menu-菜单, button-按钮, api-接口
	Identifier  string `orm:"size(100)" json:"identifier"` // 权限标识符，如：admin:user:create
	Method      string `orm:"size(10)" json:"method"`      // 请求方法，如：GET, POST, PUT, DELETE
	ParentId    int64  `orm:"default(0)" json:"parent_id"` // 父权限ID，用于构建权限树
	Sort        int    `orm:"default(0)" json:"sort"`      // 排序
	Status      int8   `orm:"default(1)" json:"status"`    // 1:正常, 0:禁用
}

// TableName 设置表名
func (p *Permission) TableName() string {
	return "ss_permission"
}

// GetPermissionById 根据ID获取权限信息
func GetPermissionById(id int64) (*Permission, error) {
	permission := &Permission{BaseModel: BaseModel{Id: id}}
	o := orm.NewOrm()
	err := o.Read(permission)
	return permission, err
}

// GetPermissionList 获取权限列表
func GetPermissionList(filters map[string]interface{}) ([]*Permission, error) {
	o := orm.NewOrm()
	qs := o.QueryTable(new(Permission))

	// 应用过滤条件
	if name, ok := filters["name"].(string); ok && name != "" {
		qs = qs.Filter("name__contains", name)
	}
	if module, ok := filters["module"].(string); ok && module != "" {
		qs = qs.Filter("module", module)
	}

	if permType, ok := filters["type"].(string); ok && permType != "" {
		qs = qs.Filter("type", permType)
	}

	if parentId, ok := filters["parent_id"].(int64); ok {
		qs = qs.Filter("parent_id", parentId)
	}

	if status, ok := filters["status"].(int8); ok {
		qs = qs.Filter("status", status)
	}

	// 排除已删除的记录
	qs = qs.Filter("is_deleted", 0)

	// 查询
	var permissions []*Permission
	_, err := qs.OrderBy("sort", "-id").All(&permissions)

	return permissions, err
}

// CreatePermission 创建权限
func CreatePermission(permission *Permission) (int64, error) {
	o := orm.NewOrm()
	id, err := o.Insert(permission)
	return id, err
}

// UpdatePermission 更新权限信息
func UpdatePermission(permission *Permission, fields ...string) error {
	o := orm.NewOrm()
	_, err := o.Update(permission, fields...)
	return err
}

// DeletePermission 删除权限（软删除）
func DeletePermission(id int64) error {
	o := orm.NewOrm()
	permission := &Permission{BaseModel: BaseModel{Id: id}}
	if err := o.Read(permission); err != nil {
		return err
	}

	permission.IsDeleted = 1
	_, err := o.Update(permission, "IsDeleted")
	return err
}

// 获取所有权限
func GetAllPermissions(types ...string) ([]*Permission, error) {
	o := orm.NewOrm()
	qs := o.QueryTable(new(Permission))
	var permissions []*Permission
	// 应用过滤条件
	if len(types) > 0 {
		cond := orm.NewCondition()
		for _, v := range types {
			cond = cond.Or("type", v)
		}
		qs = qs.SetCond(cond)
	}
	_, err := qs.All(&permissions)
	return permissions, err
}

// GetPermissionsByRoleId 获取角色拥有的权限列表
func GetPermissionsByRoleId(roleId int64, types ...string) ([]*Permission, error) {
	o := orm.NewOrm()
	var rolePermissions []*RolePermission

	// 通过中间表查询角色拥有的权限
	_, err := o.QueryTable("ss_role_permission").Filter("role_id", roleId).All(&rolePermissions)
	if err != nil {
		return nil, err
	}
	// 获取所有权限ID
	var permissionIDs []int
	for _, rp := range rolePermissions {
		permissionIDs = append(permissionIDs, int(rp.PermissionId))
	}
	// 获取权限列表
	var permissions []*Permission
	qs := o.QueryTable(new(Permission))
	if len(types) > 0 {
		cond := orm.NewCondition()
		for _, v := range types {
			cond = cond.Or("type", v)
		}
		qs = qs.SetCond(cond)
	}
	_, _ = qs.Filter("id__in", permissionIDs).All(&permissions)
	return permissions, nil
}

func GetPermissionsIdByRoleId(roleId int64) ([]int64, error) {
	o := orm.NewOrm()
	var rolePermissions []*RolePermission

	// 通过中间表查询角色拥有的权限
	_, err := o.QueryTable("ss_role_permission").Filter("role_id", roleId).All(&rolePermissions)
	if err != nil {
		return nil, err
	}

	// 提取权限ID
	var permissionIds []int64
	for _, rp := range rolePermissions {
		permissionIds = append(permissionIds, rp.PermissionId)
	}

	return permissionIds, nil
}

// GetPermissionTree 获取权限树
func GetPermissionTree() ([]*Permission, error) {
	// 获取所有权限
	permissions, err := GetPermissionList(map[string]interface{}{
		"status": int8(1),
	})
	if err != nil {
		return nil, err
	}

	// 构建权限树
	var rootPermissions []*Permission
	for _, perm := range permissions {
		if perm.ParentId == 0 {
			rootPermissions = append(rootPermissions, perm)
		}
	}

	return rootPermissions, nil
}

// RolePermission 角色权限关联表
type RolePermission struct {
	Id           int64 `orm:"pk;auto"`
	RoleId       int64 `orm:"index"`
	PermissionId int64 `orm:"index"`
}

// TableName 设置表名
func (rp *RolePermission) TableName() string {
	return "ss_role_permission"
}

// AdminRole 管理员角色关联表
type AdminRole struct {
	Id      int64 `orm:"pk;auto"`
	AdminId int64 `orm:"index"`
	RoleId  int64 `orm:"index"`
}

// TableName 设置表名
func (ar *AdminRole) TableName() string {
	return "ss_admin_role"
}

// 抖音管理权限
const (
	// 抖音配置管理权限
	PermissionDouyinConfigList   = "douyin:config:list"   // 查看抖音配置列表
	PermissionDouyinConfigCreate = "douyin:config:create" // 创建抖音配置
	PermissionDouyinConfigUpdate = "douyin:config:update" // 更新抖音配置
	PermissionDouyinConfigDelete = "douyin:config:delete" // 删除抖音配置
	PermissionDouyinConfigSync   = "douyin:config:sync"   // 同步抖音配置

	// 抖音团购活动管理权限
	PermissionDouyinGroupList   = "douyin:group:list"   // 查看抖音团购活动列表
	PermissionDouyinGroupCreate = "douyin:group:create" // 创建抖音团购活动
	PermissionDouyinGroupUpdate = "douyin:group:update" // 更新抖音团购活动
	PermissionDouyinGroupDelete = "douyin:group:delete" // 删除抖音团购活动

	// 抖音团购订单管理权限
	PermissionDouyinOrderList    = "douyin:order:list"    // 查看抖音团购订单列表
	PermissionDouyinOrderDetail  = "douyin:order:detail"  // 查看抖音团购订单详情
	PermissionDouyinOrderProcess = "douyin:order:process" // 处理抖音团购订单
	PermissionDouyinOrderUse     = "douyin:order:use"     // 使用抖音团购订单
	PermissionDouyinOrderSync    = "douyin:order:sync"    // 同步抖音团购订单
)
